package com.hang.ad.index.district;

import com.hang.ad.index.IndexAware;
import com.hang.ad.search.vo.feature.DistrictFeature;
import com.hang.ad.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UnitDistrictIndex implements IndexAware<String, Set<Long>> {
    private static Map<String, Set<Long>> districtMap;
    private static Map<Long, Set<String>> unitIdMap;
    static {
        districtMap = new ConcurrentHashMap<>();
        unitIdMap = new ConcurrentHashMap<>();
    }

    @Override
    public Set<Long> get(String key) {
        return districtMap.get(key);
    }

    @Override
    public void update(String key, Set<Long> value) {
        log.error("不支持update");
    }

    @Override
    public void add(String key, Set<Long> value) {
        Set<Long> unitIds = CommonUtils.getOrCreate(key, districtMap, ConcurrentSkipListSet::new);
        unitIds.addAll(value);
        for (Long id : value){
            Set<String> districts = CommonUtils.getOrCreate(id, unitIdMap, ConcurrentSkipListSet::new);
            districts.add(key);
        }
    }

    @Override
    public void delete(String key, Set<Long> value) {
        Set<Long> unitIds = CommonUtils.getOrCreate(key, districtMap, ConcurrentSkipListSet::new);
        unitIds.removeAll(value);
        for (Long id : value){
            Set<String> districts = CommonUtils.getOrCreate(id, unitIdMap, ConcurrentSkipListSet::new);
            districts.remove(key);
        }
    }


    public boolean match(Long unitId, List<DistrictFeature.ProvinceAndCity> districts){
        if (districtMap.containsKey(unitId) && CollectionUtils.isNotEmpty(districtMap.get(unitId))){
            Set<Long>  unitDistricts = districtMap.get(unitId);
            List<String> collect = districts.stream().map(d -> CommonUtils.stringConcat(d.getProvince(), d.getCity())).collect(Collectors.toList());
            return CollectionUtils.isSubCollection(collect, unitDistricts);
        }
        return false;
    }
}
